package com.itbaizhan;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

public class TestTransformer implements ClassFileTransformer {


    private final String CLASSNAME = "com.itbaizhan.controller.HelloController";

    private final String METHODNAME = "hello";


    // 这个接口的目的就是在class被装载到JVM之前将class字节码转换掉，从而达到动态注入代码的目的。
    @Override
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {

        //className:com/itbaizhan/controller/HelloController
//        System.out.println("className:" + className);

        String finalClassName = className.replace("/", ".");
        // 判断classname是不是我们的目标
        if (finalClassName.equals(CLASSNAME)){
            System.out.println("class name 匹配上了");

            CtClass ctClass;
            try {
                // 获取hellocontroller class
                ctClass = ClassPool.getDefault().get(CLASSNAME);
                System.out.println("class is ok ！！！");
                CtMethod declaredMethod = ctClass.getDeclaredMethod(METHODNAME);
                System.out.println("method is ok !!!!");
                declaredMethod.insertBefore("System.out.println(\" 字节码添加成功打印日志 \");");
                return ctClass.toBytecode();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }
}
